//
//  FriendsViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/17/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "FriendsViewController.h"

#import "InviteViewController.h"
#import "WebRequest.h"

#import "SDImageView+SDWebCache.h"


#import "PersonalViewController.h"

#import "FriendListCellView.h"


#define kFriendsTitle @"已有好友"
#define kAwaitTitle @"好友请求"

static WebConnection      *friends_connection;
static WebConnectionArray      *friendHandle_connection;

static FriendEditType editType = 0;
static NSInteger editSectionIndex = -1;

@interface FriendsViewController ()

@end

@implementation FriendsViewController


@synthesize mytabelView;

@synthesize tableSections;

@synthesize dataSourceDict;


- (void)dealloc
{
    
    [mytabelView release];
    
    [tableSections release];
    [dataSourceDict release];
    
    if (friends_connection != nil) {
        
        friends_connection.connectionDelegate = nil;
        [friends_connection release];
        friends_connection = nil;
        
    }
    
    if (friendHandle_connection != nil) {
        
        friendHandle_connection.connectionDelegate = nil;
        [friendHandle_connection release];
        friendHandle_connection = nil;
    }

    CLog(@"FriendsView released!");
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    editType = kEditNone;
    editSectionIndex = -1;
    
    //self.navigationController.navigationBar.delegate = self;
    
    //定义返回按钮
    UIBarButtonItem * backBarButtonItem=[[UIBarButtonItem alloc] initWithTitle: @"返回" style:UIBarButtonSystemItemDone target:self action: nil];   
    
    [[self navigationItem] setBackBarButtonItem:backBarButtonItem];  
    [backBarButtonItem release];
    
    self.navigationItem.title = @"好友";


}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
        
    [mytabelView setEditing:NO animated:NO];
    [self loadTableData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark Load Data
- (void)loadTableData
{
    if (tableSections== nil) {
        tableSections = [[NSMutableArray alloc] init];  

    }
    if (dataSourceDict == nil) {
        dataSourceDict = [[NSMutableDictionary alloc] init];
    }
    
    [tableSections removeAllObjects];
    [dataSourceDict removeAllObjects];
    
    //邀请好友
    [tableSections addObject:@"添加好友"];
    
    //邀请/被邀请
    [tableSections addObject:kAwaitTitle];
    
    //好友
    [tableSections addObject:kFriendsTitle];
    
    if (NETWORK_STATUS_UNLOADING) {
        
        int uid = [[[NSUserDefaults standardUserDefaults]valueForKey:@"userId"] intValue];
        NSMutableURLRequest * request = [WebRequest allFriendsWith:uid];
        CLog(@"request %@", request);
        
        if (friends_connection != nil) {
            friends_connection.connectionDelegate = nil;
        }
        friends_connection = [[WebConnection alloc] initWith:request delegate:self dataBaseListName:nil];
    }
    else{
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"哎呀，网络好像有问题，无法获取好友列表！" duration:DEFAULT_LOADING_TIME *1.2];
    }
    
    
    
    
    /**********临时测试**********/
    //手动邀请好友
//    NSArray *valueArray = [NSArray arrayWithObjects:@"398", @"26", nil];
//    NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"fuid", nil];
//    
//    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
//    
//    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
//    
//    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];;
//    
//    NSMutableURLRequest *request1 = [WebRequest inviteFriend:jsonData];
//    
//    WebConnection *connection = [[WebConnection alloc] initWith:request1 delegate:nil dataBaseListName:nil];

    /**********临时测试**********/
    
}

#pragma mark -
#pragma mark connectionDelegate

- (void)connectionSuccess:(NSDictionary *)dict
{
    //CLog(@"dict %@  retain count %d", dict, [dict retainCount]);    
    NSNumber *count = [dict objectForKey:@"totalCount"];
    
    
    if (count >0) {
        NSArray *friendsArray = [dict objectForKey:@"result"];
       
        for (NSDictionary *friendDict in friendsArray) {
            
            CLog(@"dict %@", friendDict);
            
             NSString *statusCode = [friendDict objectForKey:@"statusCode"];
            
            CLog(@"state %@", statusCode);
            
            //未接受  等待…
            if ([statusCode isEqualToString:@"unhandle"] ) { 
                
                NSMutableArray *array = [dataSourceDict objectForKey:kAwaitTitle];
                
                if (array == nil) {
                    array = [[NSMutableArray alloc] init];
                    [dataSourceDict setObject:array forKey:kAwaitTitle];
                    [array release];
                }
                
                [array addObject:friendDict];

            }
            else if([statusCode isEqualToString:@"accept"]|| [statusCode isEqualToString:@"await"]){     //好友
                NSMutableArray *array = [dataSourceDict objectForKey:kFriendsTitle];
                
                if (array == nil) {
                    array = [[NSMutableArray alloc] init];
                    [dataSourceDict setObject:array forKey:kFriendsTitle];
                    [array release];
                }
                
                [array addObject:friendDict];

            }

        }
    }
     
    
    [self.mytabelView reloadData];
    
}

- (void)connectionError:(NSError *)error
{
    CLog(@"connectionError");
}

- (void)connectionArraySuccess:(NSDictionary *)dict  connectionURL:(NSString *)url
{
    CLog(@"dict %@", dict);
    
    [LoadingView hideWithAnimated:NO];
    
    BOOL isSuccess = [[dict objectForKey:@"object"] boolValue];
    
    if (editType != kEditNone) {
        
        if (isSuccess) {
            switch (editType) {
                case kAcceptFriend:
                {
                    //接受
                    NSMutableArray *array = [dataSourceDict objectForKey:kAwaitTitle];
                    
                    NSDictionary *friendDict = [array objectAtIndex:editSectionIndex];
                    
                    NSMutableArray *friendsArray = [dataSourceDict objectForKey:kFriendsTitle];
                    
                    if (friendsArray == nil) {
                        friendsArray = [[NSMutableArray alloc] init];
                        [dataSourceDict setObject:friendsArray forKey:kFriendsTitle];
                        [friendsArray release];
                    }
                    [friendsArray addObject:friendDict];

                    
                    [array removeObjectAtIndex:editSectionIndex];
                    
                    [self.mytabelView reloadData];
                    
                    [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"成功！"];
                    break;
                }
                case kRejectFriend:
                {
                    //拒绝
                    NSMutableArray *array = [dataSourceDict objectForKey:kAwaitTitle];
                    
                    [array removeObjectAtIndex:editSectionIndex];
                    
                    [self.mytabelView reloadData];
                    
                    [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"成功！"];
                    break;
                } 
                case kDeleteFriend:
                {
                    //删除
                    NSMutableArray *array = [dataSourceDict objectForKey:kFriendsTitle];
                    
                    [array removeObjectAtIndex:editSectionIndex];
                    
                    [self.mytabelView reloadData];
                    
                    [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"成功！"];
                    break;
                } 
                default:
                {
                    [LoadingView hideWithAnimated:YES];
                    break;
                }
            }
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"操作失败！"];
        }
        
        editType = kEditNone;
        editSectionIndex = -1;
    }

    
}

- (void)connectionArrayError:(NSError *)error
{
    CLog(@"dict %@", error);
    [LoadingView hideWithAnimated:YES];
    if (editType != kEditNone) {
        switch (editType) {
            case kAcceptFriend:
            {
                //接受
                [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"接受请求失败，请重新处理！"];
                break;
            }
            case kRejectFriend:
            {
                //拒绝
                [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"忽略请求失败，请重新处理！"];
                break;
            } 
            case kDeleteFriend:
            {
                //删除
                [LoadingView showDurationMessageLoadingViewWith:kDefaultTipsLoadingDuration message:@"删除好友失败，请重新处理！"];
                break;
            } 
            default:
                break;
        }
        
        editType = kEditNone;
        editSectionIndex = -1;
    }
    
    
}



#pragma mark -
#pragma mark UITableViewDelegate and UITableViewDatasource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.tableSections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    NSString *key = [tableSections objectAtIndex:section];
    NSArray *array = [dataSourceDict objectForKey:key];
    
    if (array == nil || row > [array count]) {
        return nil;
    }
    
    
    NSDictionary *dict = [array objectAtIndex:row];
    NSString *friendName = [dict objectForKey:@"friendUserName"];
    NSInteger userId = [[dict objectForKey:@"friendUserId"] intValue];

    
    static NSString *MyIdentifier = @"FriendListCellView";
	// Try to retrieve from the table view a now-unused cell with the given identifier.
	FriendListCellView *cell =(FriendListCellView *) [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	
    if (cell == nil) {
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FriendListCellView" 
                                                     owner:self options:nil];
#ifdef __IPHONE_2_1
		cell = (FriendListCellView *)[nib objectAtIndex:0];
#else
		cell = (FriendListCellView *)[nib objectAtIndex:1];
#endif
        
        cell.imageView.layer.cornerRadius =3;
        cell.imageView.clipsToBounds = YES;
        
        switch (section) {
            case 1:
            {
                //接受
                UIButton *acceptButton = [[UIButton alloc] initWithFrame:CGRectMake(250, CGRectGetHeight(cell.frame) /2 - 25.0/2, 50, 25)];
                [acceptButton setImage:[UIImage imageNamed:@"button1bg_friend1_iphone.png"] forState:UIControlStateNormal];
                [acceptButton addTarget:self action:@selector(acceptInviteAction:) forControlEvents:UIControlEventTouchUpInside];
                acceptButton.tag = row;
                
                UILabel *acceptLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(acceptButton.frame), CGRectGetHeight(acceptButton.frame))];
                [acceptLabel setTextAlignment:UITextAlignmentCenter];
                [acceptLabel setText:@"接受"];
                [acceptLabel setFont:[UIFont systemFontOfSize:14]];
                acceptLabel.tag = 110;
                [acceptLabel setBackgroundColor:[UIColor clearColor]];
                [acceptButton addSubview:acceptLabel];
                [acceptLabel release];
                
                [cell addSubview:acceptButton];
                [acceptButton release];
                
                //拒绝
                UIButton *rejectButton = [[UIButton alloc] initWithFrame:CGRectMake(197, CGRectGetHeight(cell.frame) /2 - 25.0/2, 50, 25)];
                [rejectButton setImage:[UIImage imageNamed:@"button1bg_friend1_iphone.png"] forState:UIControlStateNormal];
                [rejectButton addTarget:self action:@selector(rejectInviteAction:) forControlEvents:UIControlEventTouchUpInside];
                rejectButton.tag = row;
                
                UILabel *rejectLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(acceptButton.frame), CGRectGetHeight(acceptButton.frame))];
                [rejectLabel setFont:[UIFont systemFontOfSize:14]];
                [rejectLabel setTextAlignment:UITextAlignmentCenter];
                [rejectLabel setText:@"拒绝"];
                [rejectLabel setBackgroundColor:[UIColor clearColor]];
                rejectLabel.tag = 110;
                
                [rejectButton addSubview:rejectLabel];
                [rejectLabel release];

                [cell addSubview:rejectButton];
                [rejectButton release];
                
                //个人主页
//                UIButton *userButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
//                userButton.tag = row;
//                userButton.center = CGPointMake(100, cell.frame.size.height /2);
//                [userButton setBackgroundColor:[UIColor redColor]];
//                [userButton addTarget:self action:@selector(toUserViewAction:) forControlEvents:UIControlEventTouchUpInside];
//                [cell addSubview:userButton];
                
                cell.imageButton.tag = row;
                [cell.imageButton addTarget:self action:@selector(toUserViewAction:) forControlEvents:UIControlEventTouchUpInside];
               
                break;
            }
            case 2:
            {
                //个人主页
//                UIButton *userButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
//                userButton.tag = row;
//                userButton.center = CGPointMake(100, cell.frame.size.height /2);
//                [userButton setBackgroundColor:[UIColor redColor]];
//                [userButton addTarget:self action:@selector(toFriendViewAction:) forControlEvents:UIControlEventTouchUpInside];
//                [cell addSubview:userButton];
                
                cell.imageButton.tag = row;
                [cell.imageButton addTarget:self action:@selector(toFriendViewAction:) forControlEvents:UIControlEventTouchUpInside];
                
                break;
            }
            default:
                break;
        }
        if (section == 1) {
            
        }
        
	}
    
    for (UIView *subView in [cell subviews]) {

        subView.tag = row;
    }
    
    NSString *statusCode = [dict objectForKey:@"statusCode"];
    
    if (section == 2 && [statusCode isEqualToString:@"await"]){
        friendName = [friendName stringByAppendingFormat:@"(等待回复)"];
    }
    cell.textLabel.text = friendName;
   	
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    //ICON
    if(![[dict objectForKey:@"friendUserAttachmentId"] isMemberOfClass:[NSNull class]]){
        //http://ucenter.meet-future.net/gravatar/1/30x30
        NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",UCENTERBASEURL,@"/gravatar",[dict objectForKey:@"friendUserAttachmentId"]];
        NSURL *url = [NSURL URLWithString:string];	
        [cell.imageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon];
	}
    
    [cell setSelected:NO];
    
	return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if(section == 2){
        return YES;
    }
    else {
        return NO;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 2) {
        return UITableViewCellEditingStyleDelete;
    } else {
        return UITableViewCellEditingStyleNone;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除好友";
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = section;
    
    
    [button addTarget:self action:@selector(headerClicked:) forControlEvents:UIControlEventTouchUpInside];

    if (section == 0) {
        UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(281, 12, 25, 25)];
        image.image = [UIImage imageNamed:@"icon_jiantou_iphone.png"];
        [button addSubview:image];
        [image release];
        
        [button setBackgroundColor:[UIColor colorWithRed:235.0/255.0 green:223.0/255.0 blue:207.0/255 alpha:1.0]];
    }
    else {
        [button setBackgroundImage:[UIImage imageNamed:@"barbg_friend1_iphone.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"barbg_friend1_iphone.png"] forState:UIControlStateHighlighted];
        [button setShowsTouchWhenHighlighted:NO];

    }
    
    CGFloat size = 14;
    CGFloat width = [[self.tableSections objectAtIndex:section] sizeWithFont:[UIFont boldSystemFontOfSize:size]].width;
    while(width > 300){
        size -= 1.0;
        width = [[self.tableSections objectAtIndex:section] sizeWithFont:[UIFont boldSystemFontOfSize:--size]].width;
    }
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 50)];
    [label setBackgroundColor:[UIColor clearColor]];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:14];
    
    NSString *titleStr = [self.tableSections objectAtIndex:section];
    label.text = titleStr;
    [label setTextAlignment:UITextAlignmentLeft];
    [button addSubview:label];
    [label release];
    
    button.layer.shadowOffset =CGSizeMake(0, 1);
    button.layer.shadowColor = [[UIColor blackColor] CGColor];
    button.layer.shadowOpacity = 0.7;
    
    
    NSString *key = [tableSections objectAtIndex:section];
    NSArray *array = [dataSourceDict objectForKey:key];
    
    if (section == 2 &&[array count] >0) {
        UIButton *editButton = [[UIButton alloc] initWithFrame:CGRectMake(250, 50 , 50, 25)];
        
        [editButton setImage:[UIImage imageNamed:@"button2bg_friend1_iphone.png"] forState:UIControlStateNormal];
        [editButton setBackgroundColor:[UIColor clearColor]];
        [editButton addTarget:self action:@selector(friendsListEditAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [editButton setCenter:CGPointMake(275, 25)];
        
        UILabel *editLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(editButton.frame), CGRectGetHeight(editButton.frame))];
        [editLabel setTextAlignment:UITextAlignmentCenter];
        if (mytabelView.isEditing) {
            [editLabel setText:@"完成"];
        }
        else {
            [editLabel setText:@"编辑"];
        }
        editLabel.tag = 110;
        
        editLabel.font = [UIFont boldSystemFontOfSize:14];
        [editLabel setBackgroundColor:[UIColor clearColor]];
        
        [editButton addSubview:editLabel];
        [editLabel release];
        
        [button addSubview:editButton];
        [editButton release];

    }
    
    return button;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.highlighted = NO;
    cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
    
}

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (NETWORK_STATUS_LOADING) {
        NSInteger section = indexPath.section;
        NSInteger index = indexPath.row;
        
        CLog(@"delete friend index %d", index);
        
        NSString *key = [tableSections objectAtIndex:section];
        NSMutableArray *array = [dataSourceDict objectForKey:key];
        
        
        NSDictionary *dict = [array objectAtIndex:index];
        NSString *fid = [dict objectForKey:@"id"];
        
        NSMutableURLRequest * request = [WebRequest gnoreFriendInvite:fid.intValue];
        CLog(@"request %@", request);
        
        [LoadingView showDefaultLoadingView];
        editType = kDeleteFriend;
        editSectionIndex = index;
        if (friendHandle_connection != nil) {
            friendHandle_connection.connectionDelegate = nil;
        }
        friendHandle_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
	
}


-(void)headerClicked:(id)sender{
    UIButton *button = (UIButton *)sender;
    
    NSInteger section = button.tag;
    switch (section) {
        case 0:
        {
            
            InviteViewController *content = [[InviteViewController alloc] init] ;
            
            [self.navigationController pushViewController:content animated:YES];
            [content release];
            
            CLog(@"邀请好友");
            break;
        }   
        default:
            break;
    }

}

-(int)numberOfRowsInSection:(NSInteger)section{
    
    NSString *key = [tableSections objectAtIndex:section];
    
    NSArray *array = [dataSourceDict objectForKey:key];
    
    if (array != nil) {
        return [array count];
    }
    else {
        return 0;
    } 
        

}

#pragma mark -
#pragma mark UINavigationBarDelegate
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item
{
    CLog(@"shouldPushItem");
    
    return NO;
}// called to push. return NO not to.
- (void)navigationBar:(UINavigationBar *)navigationBar didPushItem:(UINavigationItem *)item
{
    CLog(@"didPushItem");
}// called at end of animation of push or immediately if not animated
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    CLog(@"shouldPopItem");
    return YES;
}// same as push methods
- (void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item
{
    CLog(@"didPopItem");
}

#pragma mark -
#pragma mark Action

- (void)toUserViewAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSInteger index = button.tag;
    
    CLog(@"index %d", index);
    
    NSString *key = [tableSections objectAtIndex:1];
    NSMutableArray *array = [dataSourceDict objectForKey:key];
    
    NSDictionary *dict = [array objectAtIndex:index];
    
    int fid = [[dict objectForKey:@"friendUserId"] intValue];
    
    CLog(@"Friend uid %d", fid);
    

    PersonalViewController *personalViewController = [[PersonalViewController alloc] initWithUserId:fid];
    
    [self.navigationController pushViewController:personalViewController animated:YES];
    
    [personalViewController release];

}

- (void)toFriendViewAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSInteger index = button.tag;
    
    CLog(@"index %d", index);
    
    NSString *key = [tableSections objectAtIndex:2];
    NSMutableArray *array = [dataSourceDict objectForKey:key];
    
    NSDictionary *dict = [array objectAtIndex:index];
    
    int fid = [[dict objectForKey:@"friendUserId"] intValue];
    
    CLog(@"Friend uid %d", fid);
    
    PersonalViewController *personalViewController = [[PersonalViewController alloc] initWithUserId:fid];
    
    [self.navigationController pushViewController:personalViewController animated:YES];
    
    [personalViewController release];
}


- (void)acceptInviteAction:(id)sender
{

    
    if (NETWORK_STATUS_LOADING) {
        UIButton *button = (UIButton *)sender;
        
        NSInteger index = button.tag;
        
        CLog(@"accept index %d", index);
        
        NSString *key = [tableSections objectAtIndex:1];
        NSMutableArray *array = [dataSourceDict objectForKey:key];
        
        NSDictionary *dict = [array objectAtIndex:index];

        NSString *fid = [dict objectForKey:@"id"];
        
        NSMutableURLRequest * request = [WebRequest acceptFriendInvite:fid.intValue];
        CLog(@"request %@", request);
        
        [LoadingView showDefaultLoadingView];
        editType = kAcceptFriend;
        editSectionIndex = index;
        if (friendHandle_connection != nil) {
            friendHandle_connection.connectionDelegate = nil;
        }
        friendHandle_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
    
}

- (void)rejectInviteAction:(id)sender
{
    
    if (NETWORK_STATUS_LOADING) {
        
        UIButton *button = (UIButton *)sender;
        
        NSInteger index = button.tag;
        
        CLog(@"reject index %d", index);
        
        NSString *key = [tableSections objectAtIndex:1];
        NSMutableArray *array = [dataSourceDict objectForKey:key];
        
        
        NSDictionary *dict = [array objectAtIndex:index];
        NSString *fid = [dict objectForKey:@"id"];
        
        NSMutableURLRequest * request = [WebRequest gnoreFriendInvite:fid.intValue];
        CLog(@"request %@", request);
        
        [LoadingView showDefaultLoadingView];
        editType = kRejectFriend;
        editSectionIndex = index;
        if (friendHandle_connection != nil) {
            friendHandle_connection.connectionDelegate = nil;
        }
        friendHandle_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];

    }

}

- (void)friendsListEditAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    UILabel *label = (UILabel *)[button viewWithTag:110];
    
    BOOL isEditing = mytabelView.isEditing;
    
    if (isEditing) {
        label.text = @"编辑";
    }
    else {
        label.text = @"完成";
    }
    
    [mytabelView setEditing:!isEditing animated:YES];
}

- (void)deleteFriendAction:(id)sender
{
    if (NETWORK_STATUS_LOADING) {
        
        UIButton *button = (UIButton *)sender;
        
        NSInteger index = button.tag;
        
        CLog(@"delete friend index %d", index);
        
        NSString *key = [tableSections objectAtIndex:2];
        NSMutableArray *array = [dataSourceDict objectForKey:key];
        
        
        NSDictionary *dict = [array objectAtIndex:index];
        NSString *fid = [dict objectForKey:@"id"];
        
        NSMutableURLRequest * request = [WebRequest gnoreFriendInvite:fid.intValue];
        CLog(@"request %@", request);
        
        [LoadingView showDefaultLoadingView];
        editType = kDeleteFriend;
        editSectionIndex = index;
        if (friendHandle_connection != nil) {
            friendHandle_connection.connectionDelegate = nil;
        }
        friendHandle_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    }
    
    
}

#pragma mark textField delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.text = @"";
    [textField setTextColor:[UIColor darkGrayColor]];
    
}

-(NSString *)changeStringFommat:(NSString *)str{
    
    PublicMethodEngine *methodEngine = [PublicMethodEngine sharedPublicMethodEngine];   
    
    return  [methodEngine changeStringFommat:str];
    
    
    
}





@end
